import { defineStore } from 'pinia';
import { ref } from 'vue';
import { loginApi } from '@renderer/api/auth/index';
import { LoginData } from '@renderer/api/auth/types/index';

export const useUserStore = defineStore('user', () => {
  const token = ref('');
  const user = ref('');

  function login(data: LoginData) {
    return new Promise<boolean>((resolve) => {
      loginApi(data)
        .then((res) => {
          console.log(res);
          localStorage.setItem('token', 'Bearer ' + res.data.token); // Bearer eyJhbGciOiJIUzI1NiJ9.xxx.xxx
          const user = JSON.stringify(res.data.user);
          localStorage.setItem('user', user);
          resolve(true);
        })
        .catch((res) => {
          console.log('false', res);
          resolve(false);
        });
    });
  }

  function getUser() {
   const u = localStorage.getItem('user');
   if(u) {
    user.value = u
   }

    return user.value;
  }

  return { token, login, getUser };
});
